package com.superhelper.superhelper_web.interceptor;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.superhelper.common.Consts;
import com.superhelper.common.service.RedisService;
import com.superhelper.common.utils.JsonHelper;
import com.superhelper.common.utils.TimeCostHelper;
import com.superhelper.superhelper_web.common.CommonHelper;
import com.superhelper.superhelper_web.domain.Admin;
import com.superhelper.superhelper_web.domain.Resp;
import com.superhelper.superhelper_web.mapper.AdminMapper;

/**
 * 请求拦截
 * 
 * @author duanshao
 * 
 */
public class URIInterceptor extends HandlerInterceptorAdapter {

	private final Logger LOG = LoggerFactory.getLogger("access");

	private String[] excludeMethods = { "admin/login.do", "admin/index.do",
			"register_e.do", "register.do", "callback.do",
			"admin/order/print.do", "admin/info.do" };

	@Autowired
	private AdminMapper adminMapper;
	@Autowired
	private RedisService redis;

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		Map<String, Object> carrier = new HashMap<String, Object>();
		carrier.put("request", request.getQueryString());
		carrier.put("uri", request.getRequestURI());
		TimeCostHelper.watch(carrier);
		String baseLogin = request.getContextPath();
		Admin admin = CommonHelper.getSessionUser();
		boolean flag = false;
		if (null == admin) { // 用户没登陆
			String requestURL = request.getRequestURI(); // 获取URL
			for (String url : excludeMethods) { // 循环URL
				if (requestURL.indexOf(url) >= 0) {
					flag = true;
					break;
				}
			}
			if (!flag) { // flag话就到登陆页面
				// StringBuffer sb = new StringBuffer();
				// sb.append("<script>");
				// sb.append("alert('用户已失效，请重新登录');");
				// sb.append("</script>");
				//
				// sb.append("<script>");
				// sb.append("top.window.location='" + baseLogin + "'");
				// sb.append("</script>");
				Resp resp = new Resp(-2, "回话过期");
				String body = JsonHelper.toJson(resp);
				response.setContentType("text/html");
				response.setCharacterEncoding("utf-8");
				response.getOutputStream().write(body.getBytes("UTF-8"));
				response.getOutputStream().flush();
			}
		} else {
			String online_key = String.format(Consts.Redis.USER_ONLINE,
					admin.getId());
			redis.set(online_key, 300, admin);// 5分钟不没有访问，表示离线
			flag = true;
		}
		return flag;
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		LOG.info("cost:{};uri:{}", TimeCostHelper.getTimeCost(),
				request.getRequestURI());
		TimeCostHelper.clean();
	}

	public String[] getExcludeMethods() {
		return excludeMethods;
	}

	public void setExcludeMethods(String[] excludeMethods) {
		this.excludeMethods = excludeMethods;
	}
}
